<?php
require_once __DIR__ . '/../functions.php';

// 检查管理员权限
if (!isAdmin()) {
    redirect('../index.php', '您没有权限访问此页面', 'danger');
}

$results = [];
$uploadedFile = null;

// 使用SESSION保存查询结果，避免页面刷新丢失
if (isset($_GET['clear']) && $_GET['clear'] == '1') {
    unset($_SESSION['batch_query_results']);
    unset($_SESSION['batch_query_file']);
    header('Location: batch_query.php');
    exit;
}

// 如果有保存的查询结果，优先使用
if (isset($_SESSION['batch_query_results']) && !isset($_POST['action'])) {
    $results = $_SESSION['batch_query_results'];
    $uploadedFile = $_SESSION['batch_query_file'] ?? null;
}

// 处理文件上传和查询
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'query') {
    if (!isset($_FILES['tracking_file']) || $_FILES['tracking_file']['error'] !== UPLOAD_ERR_OK) {
        $error = '请选择要上传的文件';
    } else {
        $file = $_FILES['tracking_file'];
        $uploadedFile = $file['name'];
        
        // 检查文件类型
        $allowedTypes = ['text/plain', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'text/csv'];
        $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        
        if (!in_array($file['type'], $allowedTypes) && !in_array($fileExtension, ['txt', 'csv', 'xls', 'xlsx'])) {
            $error = '不支持的文件类型，请上传 TXT、CSV 或 Excel 文件';
        } else {
            try {
                $trackingNumbers = [];
                
                if ($fileExtension == 'txt' || $fileExtension == 'csv') {
                    // 处理文本文件
                    $content = file_get_contents($file['tmp_name']);
                    $lines = explode("\n", $content);
                    
                    foreach ($lines as $line) {
                        $line = trim($line);
                        if (!empty($line)) {
                            $trackingNumbers[] = $line;
                        }
                    }
                } elseif (in_array($fileExtension, ['xls', 'xlsx'])) {
                    // 处理Excel文件
                    require_once __DIR__ . '/../vendor/autoload.php';
                    
                    $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file['tmp_name']);
                    $worksheet = $spreadsheet->getActiveSheet();
                    
                    foreach ($worksheet->getRowIterator() as $row) {
                        $cellIterator = $row->getCellIterator();
                        $cellIterator->setIterateOnlyExistingCells(false);
                        
                        foreach ($cellIterator as $cell) {
                            $value = trim($cell->getValue());
                            if (!empty($value)) {
                                $trackingNumbers[] = $value;
                                break; // 只取每行第一列
                            }
                        }
                    }
                }
                
                if (empty($trackingNumbers)) {
                    $error = '文件中没有找到有效的物流单号';
                } else {
                    // 查询订单
                    $db = getDB();
                    
                    foreach ($trackingNumbers as $trackingNo) {
                        $stmt = $db->prepare("SELECT o.*, u.username, u.phone, u.group_name FROM orders o 
                                           LEFT JOIN users u ON o.user_id = u.id 
                                           WHERE o.tracking_no = ?");
                        $stmt->execute([$trackingNo]);
                        $order = $stmt->fetch();
                        
                        if ($order) {
                            $order['delivery_location_label'] = getConfigOptionLabel('delivery_location', $order['delivery_location']);
                            $order['order_platform_label'] = getConfigOptionLabel('order_platform', $order['order_platform']);
                            $order['payment_method_label'] = getPaymentMethodText($order['payment_method']);
                            $results[] = [
                                'tracking_no' => $trackingNo,
                                'found' => true,
                                'order' => $order
                            ];
                        } else {
                            $results[] = [
                                'tracking_no' => $trackingNo,
                                'found' => false,
                                'order' => null
                            ];
                        }
                    }
                    
                    // 保存查询结果到SESSION
                    $_SESSION['batch_query_results'] = $results;
                    $_SESSION['batch_query_file'] = $uploadedFile;
                    
                    $success = '查询完成，共处理 ' . count($trackingNumbers) . ' 个物流单号';
                }
            } catch (Exception $e) {
                $error = '文件处理失败：' . $e->getMessage();
            }
        }
    }
}

// 防重复提交token
if (!isset($_SESSION['form_tokens'])) {
    $_SESSION['form_tokens'] = [];
}

// 生成新的token
$currentToken = md5(uniqid(mt_rand(), true) . $_SERVER['REMOTE_ADDR']);
$_SESSION['form_tokens'][] = $currentToken;
// 保持最近50个token
if (count($_SESSION['form_tokens']) > 200) {
    array_shift($_SESSION['form_tokens']);
}

include __DIR__ . '/header.php';
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">批量查询</h1>
    <?php if (!empty($results)): ?>
        <div class="btn-group">
            <a href="batch_query.php?clear=1" class="btn btn-warning">
                <i class="bi bi-trash"></i> 清除查询
            </a>
        </div>
    <?php endif; ?>
</div>

<?php if (isset($error)): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="bi bi-exclamation-triangle-fill"></i> <?php echo htmlspecialchars($error); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<?php if (isset($success)): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="bi bi-check-circle-fill"></i> <?php echo htmlspecialchars($success); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<!-- 上传表单 -->
<div class="card mb-4">
    <div class="card-header bg-primary text-white">
        <h5 class="mb-0">
            <i class="bi bi-upload"></i> 上传物流单号文件
        </h5>
    </div>
    <div class="card-body">
        <form method="POST" enctype="multipart/form-data" class="needs-validation" novalidate>
            <input type="hidden" name="action" value="query">
            
            <div class="mb-3">
                <label for="tracking_file" class="form-label">
                    <i class="bi bi-file-earmark-text"></i> 选择文件 <span class="text-danger">*</span>
                </label>
                <input type="file" class="form-control" id="tracking_file" name="tracking_file" 
                       accept=".txt,.csv,.xls,.xlsx" required>
                <div class="form-text">
                    支持的文件格式：TXT、CSV、Excel（.xls、.xlsx）<br>
                    文件内容要求：每行一个物流单号，或Excel文件每行第一列为物流单号
                </div>
            </div>
            
            <div class="mb-3">
                <div class="alert alert-info">
                    <i class="bi bi-info-circle"></i>
                    <strong>使用说明：</strong>
                    <ul class="mb-0 mt-2">
                        <li>TXT文件：每行一个物流单号</li>
                        <li>CSV文件：每行一个物流单号</li>
                        <li>Excel文件：每行第一列为物流单号</li>
                        <li>系统会自动匹配数据库中的订单信息</li>
                        <li>查询结果可以进行批量操作</li>
                    </ul>
                </div>
            </div>
            
            <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-search"></i> 开始查询
                </button>
                <button type="button" class="btn btn-secondary" onclick="downloadTemplate()">
                    <i class="bi bi-download"></i> 下载模板
                </button>
            </div>
        </form>
    </div>
</div>

<!-- 查询结果 -->
<?php if (!empty($results)): ?>
    <div class="card">
        <div class="card-header bg-success text-white">
            <h5 class="mb-0">
                <i class="bi bi-list-check"></i> 查询结果
                <?php if ($uploadedFile): ?>
                    <small class="text-light">(文件：<?php echo htmlspecialchars($uploadedFile); ?>)</small>
                <?php endif; ?>
            </h5>
        </div>
        <div class="card-body">
            <?php
            $foundCount = count(array_filter($results, function($r) { return $r['found']; }));
            $notFoundCount = count(array_filter($results, function($r) { return !$r['found']; }));
            ?>
            
            <div class="row mb-4">
                <div class="col-md-3">
                    <div class="card bg-success text-white">
                        <div class="card-body text-center">
                            <h6 class="card-title">已找到</h6>
                            <h3 class="mb-0"><?php echo $foundCount; ?></h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-warning text-white">
                        <div class="card-body text-center">
                            <h6 class="card-title">未找到</h6>
                            <h3 class="mb-0"><?php echo $notFoundCount; ?></h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-info text-white">
                        <div class="card-body text-center">
                            <h6 class="card-title">总计</h6>
                            <h3 class="mb-0"><?php echo count($results); ?></h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-primary text-white">
                        <div class="card-body text-center">
                            <h6 class="card-title">成功率</h6>
                            <h3 class="mb-0"><?php echo count($results) > 0 ? round($foundCount / count($results) * 100) : 0; ?>%</h3>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 批量操作按钮 -->
            <div class="mb-3">
                <div class="btn-group" role="group">
                    <!-- 新增：批量登记按钮 -->
                    <button type="button" class="btn btn-outline-info" onclick="batchOperate('register')">
                        <i class="bi bi-pencil-square"></i> 批量登记
                    </button>
                    <button type="button" class="btn btn-outline-success" onclick="batchOperate('settle')">
                        <i class="bi bi-check-circle"></i> 批量结算
                    </button>
                    <button type="button" class="btn btn-outline-warning" onclick="batchOperate('refund')">
                        <i class="bi bi-arrow-return-left"></i> 批量退还
                    </button>
                    <button type="button" class="btn btn-outline-danger" onclick="batchOperate('delete')">
                        <i class="bi bi-trash"></i> 批量删除
                    </button>
                </div>
            </div>
            
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>
                                <input type="checkbox" id="selectAll" onchange="toggleSelectAll()">
                            </th>
                            <th>物流单号</th>
                            <th>登记</th>
                            <th>订单ID</th>
                            <th>商品名称</th>
                            <th>收货地</th>
                            <th>下单平台</th>
                            <th>用户</th>
                            <th>金额</th>
                            <th>付款方式</th>
                            <th>结算类型</th>
                            <th>退还</th>
                            <th>签收</th>
                            <th>状态</th>
                            <th>提交时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="resultsTableBody">
                        <?php foreach ($results as $index => $result): ?>
                            <tr class="<?php echo $result['found'] ? 'table-success' : 'table-warning'; ?>" id="row-<?php echo $result['found'] ? $result['order']['id'] : 'notfound-'.$index; ?>">
                                <td>
                                    <?php if ($result['found']): ?>
                                        <input type="checkbox" name="selected_orders[]" value="<?php echo $result['order']['id']; ?>" class="order-checkbox" data-order-id="<?php echo $result['order']['id']; ?>">
                                    <?php endif; ?>
                                </td>
                                <td class="fw-bold"><?php echo htmlspecialchars($result['tracking_no']); ?></td>
                                <td>
                                    <?php if ($result['found']): ?>
                                        <span class="badge bg-success">已找到</span>
                                    <?php else: ?>
                                        <span class="badge bg-warning">未找到</span>
                                    <?php endif; ?>
                                </td>
                                <?php if ($result['found']): ?>
                                    <?php $order = $result['order']; ?>
                                    <td><?php echo $order['id']; ?></td>
                                    <td><?php echo htmlspecialchars($order['product_name']); ?></td>
                                    <td><?php echo htmlspecialchars($order['delivery_location_label']); ?></td>
                                    <td><?php echo htmlspecialchars($order['order_platform_label']); ?></td>
                                    <td><?php echo htmlspecialchars($order['username']); ?></td>
                                    <td><?php echo formatAmount($order['order_amount']); ?></td>
                                    <td>
                                        <span class="badge bg-<?php echo $order['payment_method'] == 'group_paid' ? 'warning' : 'info'; ?>">
                                            <?php echo $order['payment_method_label']; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge bg-<?php echo getSettlementTypeClass($order['settlement_type']); ?>">
                                            <?php echo getSettlementTypeText($order['settlement_type']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge bg-<?php echo getOrderReturnClass($order['is_returned']); ?>">
                                            <?php echo getOrderReturnText($order['is_returned']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge bg-<?php echo getOrderSignClass($order['is_signed']); ?>">
                                            <?php echo getOrderSignText($order['is_signed']); ?>
                                        </span>
                                    </td>
                                    <td id="status-<?php echo $order['id']; ?>">
                                        <span class="badge bg-<?php echo getOrderStatusClass($order['status']); ?>">
                                            <?php echo getOrderStatusText($order['status']); ?>
                                        </span>
                                    </td>
                                    <td><?php echo formatTime($order['created_at']); ?></td>
                                    <td id="actions-<?php echo $order['id']; ?>">
                                        <div class="btn-group" role="group">
                                            <button type="button" class="btn btn-sm btn-outline-primary" 
                                                    onclick="showOrderDetails(<?php echo $order['id']; ?>)"
                                                    data-bs-toggle="tooltip" title="查看详情">
                                                <i class="bi bi-eye"></i>
                                            </button>
                                            
                                            <button type="button" class="btn btn-sm btn-outline-success" 
                                                    onclick="editOrder(<?php echo $order['id']; ?>)"
                                                    data-bs-toggle="tooltip" title="处理订单">
                                                <i class="bi bi-pencil"></i>
                                            </button>
                                            
                                            <?php if ($order['order_screenshot']): ?>
                                                <button type="button" class="btn btn-sm btn-outline-info" 
                                                        onclick="showImageModal('<?php echo UPLOAD_URL . 'orders/' . $order['order_screenshot']; ?>')"
                                                        data-bs-toggle="tooltip" title="订单截图">
                                                    <i class="bi bi-image"></i>
                                                </button>
                                            <?php endif; ?>
                                            
                                            <form method="POST" style="display: inline;" onsubmit="return confirm('确定要删除这个订单吗？此操作不可恢复！');">
                                                <input type="hidden" name="action" value="delete">
                                                <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
                                                <input type="hidden" name="form_token" value="<?php echo $currentToken; ?>">
                                                <button type="submit" class="btn btn-sm btn-outline-danger" 
                                                        data-bs-toggle="tooltip" title="删除">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                <?php else: ?>
                                    <td colspan="11" class="text-center text-muted">
                                        <i class="bi bi-x-circle"></i> 未找到对应的订单
                                    </td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            
            <div class="mt-3">
                <button type="button" class="btn btn-primary" onclick="exportResults()">
                    <i class="bi bi-download"></i> 导出查询结果
                </button>
                <a href="batch_query.php?clear=1" class="btn btn-warning">
                    <i class="bi bi-trash"></i> 清除查询
                </a>
            </div>
        </div>
    </div>
<?php endif; ?>

<!-- 批量结算模态框 -->
<div class="modal fade" id="batchSettlementModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">批量结算订单</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>您选择了 <span id="batchOrderCountDisplay" class="text-primary fw-bold">0</span> 个订单进行批量结算</p>
                
                <div class="mb-3">
                    <label for="staticSettlementType" class="form-label">结算类型</label>
                    <select class="form-select" id="staticSettlementType" name="settlement_type">
                        <option value="commission">结本金</option>
                        <option value="principal_commission" selected>结本金+佣金</option>
                    </select>
                </div>
                
                <div class="mb-3">
                    <label for="staticSettlementAmount" class="form-label">结算金额（可选）</label>
                    <input type="number" class="form-control" id="staticSettlementAmount" name="settlement_amount" 
                           step="0.01" min="0" placeholder="留空则根据结算类型自动计算">
                    <div class="form-text">如果留空，将根据结算类型自动计算金额</div>
                </div>
                
                <div class="mb-3">
                    <label for="staticSettlementInfo" class="form-label">结算信息</label>
                    <textarea class="form-control" id="staticSettlementInfo" name="settlement_info" 
                              rows="3" placeholder="请输入结算说明、备注等">批量结算操作</textarea>
                </div>
                
                <div class="mb-3">
                    <label for="staticSettlementScreenshots" class="form-label">结算截图（可选）</label>
                    <input type="file" class="form-control" id="staticSettlementScreenshots" name="settlement_screenshots[]" 
                           accept="image/*" multiple>
                    <div class="form-text">支持多张图片，格式：JPG、PNG、GIF，最大 5MB/张</div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="staticBatchSettlementConfirmBtn">
                    <i class="bi bi-check-circle"></i> 确认结算
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 订单详情模态框 -->
<div class="modal fade" id="orderDetailsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">订单详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="orderDetailsContent">
                <!-- 详情内容将通过AJAX加载 -->
            </div>
        </div>
    </div>
</div>

<!-- 编辑订单模态框 -->
<div class="modal fade" id="editOrderModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">处理订单</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="editOrderContent">
                <!-- 编辑内容将通过AJAX加载 -->
            </div>
        </div>
    </div>
</div>

<!-- 图片放大模态框 -->
<div class="modal fade" id="imageModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">图片预览</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body text-center">
                <img id="modalImage" src="" class="img-fluid" style="max-height: 80vh;">
            </div>
        </div>
    </div>
</div>

<?php include __DIR__ . '/footer.php'; ?>
<script>
let selectedOrders = [];
let isProcessing = false;

// 简单的提示函数
function showToast(message, type = 'info') {
    // 使用Bootstrap的Toast组件替代alert
    const toast = document.createElement('div');
    toast.className = `toast align-items-center text-white bg-${type === 'success' ? 'success' : type === 'warning' ? 'warning' : type === 'danger' ? 'danger' : 'info'} border-0`;
    toast.setAttribute('role', 'alert');
    toast.setAttribute('aria-live', 'assertive');
    toast.setAttribute('aria-atomic', 'true');
    toast.innerHTML = `
        <div class="d-flex">
            <div class="toast-body">
                ${message}
            </div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    `;
    
    const toastContainer = document.getElementById('toastContainer') || createToastContainer();
    toastContainer.appendChild(toast);
    
    const bsToast = new bootstrap.Toast(toast);
    bsToast.show();
    
    // 自动移除
    toast.addEventListener('hidden.bs.toast', () => {
        toast.remove();
    });
}

function createToastContainer() {
    const container = document.createElement('div');
    container.id = 'toastContainer';
    container.className = 'toast-container position-fixed top-0 end-0 p-3';
    container.style.zIndex = '9999';
    document.body.appendChild(container);
    return container;
}

// 初始化选中状态
function initializeSelectedOrders() {
    selectedOrders = [];
    const checkboxes = document.querySelectorAll('.order-checkbox:checked');
    checkboxes.forEach(checkbox => {
        const orderId = checkbox.getAttribute('data-order-id');
        if (orderId && !selectedOrders.includes(orderId)) {
            selectedOrders.push(orderId);
        }
    });
    updateBatchButtons();
}

// 全选/取消全选
function toggleSelectAll() {
    const selectAll = document.getElementById('selectAll');
    if (!selectAll) return;
    
    const checkboxes = document.querySelectorAll('.order-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.checked = selectAll.checked;
        const orderId = checkbox.getAttribute('data-order-id');
        if (selectAll.checked && orderId && !selectedOrders.includes(orderId)) {
            selectedOrders.push(orderId);
        } else if (!selectAll.checked && orderId) {
            selectedOrders = selectedOrders.filter(id => id !== orderId);
        }
    });
    
    updateBatchButtons();
    saveSelectedOrders();
}

// 更新批量操作按钮状态
function updateBatchButtons() {
    const batchButtons = document.querySelectorAll('[onclick^="batch"]');
    batchButtons.forEach(button => {
        button.disabled = selectedOrders.length === 0;
    });
}

// 保存选中状态
function saveSelectedOrders() {
    sessionStorage.setItem('batchQuerySelectedOrders', JSON.stringify(selectedOrders));
}

// 恢复选中状态
function restoreSelectedOrders() {
    const saved = sessionStorage.getItem('batchQuerySelectedOrders');
    if (saved) {
        selectedOrders = JSON.parse(saved);
        const checkboxes = document.querySelectorAll('.order-checkbox');
        checkboxes.forEach(checkbox => {
            const orderId = checkbox.getAttribute('data-order-id');
            checkbox.checked = orderId && selectedOrders.includes(orderId);
        });
        updateBatchButtons();
        
        const selectAll = document.getElementById('selectAll');
        if (selectAll) {
            selectAll.checked = checkboxes.length > 0 && selectedOrders.length === checkboxes.length;
        }
    }
}

// 批量操作路由
function batchOperate(action) {
    if (selectedOrders.length === 0) {
        showToast('请先选择要操作的订单', 'warning');
        return;
    }
    
    switch(action) {
        case 'register':
            if (confirm(`确定要将选中的 ${selectedOrders.length} 个订单标记为已登记吗？`)) {
                executeBatchOperation('register');
            }
            break;
        case 'settle':
            batchSettle();
            break;
        case 'refund':
            if (confirm(`确定要将选中的 ${selectedOrders.length} 个订单标记为已退还吗？`)) {
                executeBatchOperation('refund');
            }
            break;
        case 'delete':
            if (confirm(`确定要删除选中的 ${selectedOrders.length} 个订单吗？此操作不可恢复！`)) {
                executeBatchOperation('delete');
            }
            break;
    }
}

// 显示批量结算模态框
function batchSettle() {
    if (selectedOrders.length === 0) {
        showToast('请先选择要结算的订单', 'warning');
        return;
    }
    
    // 更新订单数量显示
    const countDisplay = document.getElementById('batchOrderCountDisplay');
    if (countDisplay) {
        countDisplay.textContent = selectedOrders.length;
    }
    
    // 重置表单
    const settlementType = document.getElementById('staticSettlementType');
    const settlementAmount = document.getElementById('staticSettlementAmount');
    const settlementInfo = document.getElementById('staticSettlementInfo');
    const settlementScreenshots = document.getElementById('staticSettlementScreenshots');
    
    if (settlementType) settlementType.value = 'principal_commission';
    if (settlementAmount) settlementAmount.value = '';
    if (settlementInfo) settlementInfo.value = '批量结算操作';
    if (settlementScreenshots) settlementScreenshots.value = '';
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('batchSettlementModal'));
    modal.show();
}

// 执行批量操作
function executeBatchOperation(action) {
    if (isProcessing) {
        showToast('正在处理中，请稍候...', 'warning');
        return;
    }
    
    isProcessing = true;
    
    const formData = new FormData();
    formData.append('action', action);
    formData.append('order_ids', JSON.stringify(selectedOrders));
    
    if (action === 'settle') {
        // 使用静态模态框中的输入值
        const settlementType = document.getElementById('staticSettlementType').value;
        const settlementAmount = document.getElementById('staticSettlementAmount').value;
        const settlementInfo = document.getElementById('staticSettlementInfo').value;
        const screenshotFiles = document.getElementById('staticSettlementScreenshots').files;
        
        console.log('批量查询页面 - 结算参数:', { 
            settlementType, 
            settlementAmount, 
            settlementInfo
        });
        
        formData.append('settlement_type', settlementType);
        
        // 修改：不填金额时传递空值，让后端自动计算
        if (settlementAmount !== '' && settlementAmount !== null && !isNaN(parseFloat(settlementAmount))) {
            formData.append('settlement_amount', parseFloat(settlementAmount));
        } else {
            formData.append('settlement_amount', ''); // 传递空值，后端会自动计算
        }
        
        formData.append('settlement_info', settlementInfo || '无');
        
        if (screenshotFiles.length > 0) {
            for (let i = 0; i < screenshotFiles.length; i++) {
                formData.append('settlement_screenshots[]', screenshotFiles[i]);
            }
        }
    }
    
    // 显示加载状态
    const confirmBtn = document.getElementById('staticBatchSettlementConfirmBtn');
    const originalText = confirmBtn ? confirmBtn.innerHTML : '';
    if (confirmBtn) {
        confirmBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 处理中...';
        confirmBtn.disabled = true;
    }
    
    fetch('api/batch_operations.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        console.log('服务器响应:', data);
        if (data.success) {
            showToast(data.message, 'success');
            
            // 清除选中状态
            selectedOrders = [];
            sessionStorage.removeItem('batchQuerySelectedOrders');
            
            const selectAll = document.getElementById('selectAll');
            if (selectAll) {
                selectAll.checked = false;
            }
            
            document.querySelectorAll('.order-checkbox').forEach(cb => cb.checked = false);
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('batchSettlementModal'));
            if (modal) {
                modal.hide();
            }
            
            // 刷新页面以更新数据
            setTimeout(() => {
                location.reload();
            }, 1500);
            
        } else {
            showToast(data.message, 'danger');
            if (data.errors && data.errors.length > 0) {
                console.error('批量操作错误:', data.errors);
                if (data.errors.length > 0) {
                    showToast('操作失败: ' + data.errors[0], 'danger');
                }
            }
        }
    })
    .catch(error => {
        showToast('操作失败：' + error.message, 'danger');
        console.error('操作异常:', error);
    })
    .finally(() => {
        // 恢复按钮状态
        if (confirmBtn) {
            confirmBtn.innerHTML = originalText;
            confirmBtn.disabled = false;
        }
        isProcessing = false;
    });
}

// 编辑订单
function editOrder(orderId) {
    console.log('编辑订单:', orderId);
    
    // 显示加载状态
    document.getElementById('editOrderContent').innerHTML = `
        <div class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-3">加载中...</p>
        </div>
    `;
    
    // 显示模态框
    const modalElement = document.getElementById('editOrderModal');
    const modal = new bootstrap.Modal(modalElement);
    modal.show();
    
    // 加载订单编辑表单
    fetch('api/order_edit_form_new.php?id=' + orderId)
        .then(response => response.text())
        .then(html => {
            document.getElementById('editOrderContent').innerHTML = html;
            
            // 手动触发初始化
            setTimeout(() => {
                const operationType = document.getElementById('operation_type');
                const settlementFields = document.getElementById('settlementFields');
                
                if (operationType && settlementFields) {
                    console.log('手动初始化结算字段显示');
                    if (operationType.value === 'settle_principal' || operationType.value === 'settle_commission') {
                        settlementFields.style.display = 'block';
                    } else {
                        settlementFields.style.display = 'none';
                    }
                }
            }, 200);
        })
        .catch(error => {
            console.error('加载失败:', error);
            document.getElementById('editOrderContent').innerHTML = `
                <div class="alert alert-danger">加载失败：${error.message}</div>
            `;
        });
}

// 显示图片放大模态框
function showImageModal(imageUrl) {
    document.getElementById('modalImage').src = imageUrl;
    const modal = new bootstrap.Modal(document.getElementById('imageModal'));
    modal.show();
}

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    // 恢复选中状态
    restoreSelectedOrders();
    initializeSelectedOrders();
    
    // 绑定批量结算确认按钮事件
    const batchConfirmBtn = document.getElementById('staticBatchSettlementConfirmBtn');
    if (batchConfirmBtn) {
        batchConfirmBtn.addEventListener('click', function() {
            executeBatchOperation('settle');
        });
    }
    
    // 监听单个复选框变化
    document.addEventListener('change', function(e) {
        if (e.target.classList.contains('order-checkbox')) {
            const orderId = e.target.getAttribute('data-order-id');
            if (e.target.checked && orderId && !selectedOrders.includes(orderId)) {
                selectedOrders.push(orderId);
            } else if (!e.target.checked && orderId) {
                selectedOrders = selectedOrders.filter(id => id !== orderId);
            }
            updateBatchButtons();
            saveSelectedOrders();
        }
    });
});

// 下载模板
function downloadTemplate() {
    const templateContent = `物流单号示例1
物流单号示例2
物流单号示例3
1234567890123
9876543210987`;
    
    const blob = new Blob([templateContent], { type: 'text/plain' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = '物流单号模板.txt';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
}

// 导出结果
function exportResults() {
    <?php if (!empty($results)): ?>
        let csvContent = "物流单号,查询状态,订单ID,商品名称,收货地,下单平台,用户,金额,付款方式,订单状态,提交时间\n";
        
        <?php foreach ($results as $result): ?>
            <?php if ($result['found']): ?>
                <?php $order = $result['order']; ?>
                csvContent += "<?php echo addslashes($result['tracking_no']); ?>,已找到,<?php echo $order['id']; ?>,<?php echo addslashes($order['product_name']); ?>,<?php echo addslashes($order['delivery_location_label']); ?>,<?php echo addslashes($order['order_platform_label']); ?>,<?php echo addslashes($order['username']); ?>,<?php echo $order['order_amount']; ?>,<?php echo addslashes($order['payment_method_label']); ?>,<?php echo getOrderStatusText($order['status']); ?>,<?php echo $order['created_at']; ?>\n";
            <?php else: ?>
                csvContent += "<?php echo addslashes($result['tracking_no']); ?>,未找到,,,,,,,,,\n";
            <?php endif; ?>
        <?php endforeach; ?>
        
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = '批量查询结果_<?php echo date('Ymd_His'); ?>.csv';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
    <?php else: ?>
        showToast('没有查询结果可以导出', 'warning');
    <?php endif; ?>
}

// 显示订单详情
function showOrderDetails(orderId) {
    // 显示加载状态
    document.getElementById('orderDetailsContent').innerHTML = `
        <div class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-3">加载中...</p>
        </div>
    `;
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('orderDetailsModal'));
    modal.show();
    
    // 加载订单详情
    fetch('../api/order_details.php?id=' + orderId)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const order = data.data;
                const statusClass = {
                    'pending': 'warning',
                    'settled': 'success',
                    'refunded': 'danger'
                };
                const statusText = {
                    'pending': '未结算',
                    'settled': '已结算',
                    'refunded': '已退还'
                };
                
                let html = `
                    <div class="row">
                        <div class="col-md-6">
                            <table class="table table-sm">
                                <tr><td><strong>订单ID：</strong></td><td>${order.id}</td></tr>
                                <tr><td><strong>商品名称：</strong></td><td>${order.product_name}</td></tr>
                                <tr><td><strong>收货地：</strong></td><td>${order.delivery_location_label}</td></tr>
                                <tr><td><strong>下单平台：</strong></td><td>${order.order_platform_label}</td></tr>
                                <tr><td><strong>物流单号：</strong></td><td>${order.tracking_no}</td></tr>
                                <tr><td><strong>下单金额：</strong></td><td>¥${parseFloat(order.order_amount).toFixed(2)}</td></tr>
                                <tr><td><strong>付款方式：</strong></td><td>${order.payment_method_label}</td></tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <table class="table table-sm">
                                <tr><td><strong>订单状态：</strong></td><td>
                                    <span class="badge bg-${statusClass[order.status]}">${statusText[order.status]}</span>
                                </td></tr>
                                <tr><td><strong>签收状态：</strong></td><td>
                                    <span class="badge bg-${order.is_signed ? 'success' : 'warning'}">
                                        ${order.is_signed ? '已签收' : '未签收'}
                                    </span>
                                </td></tr>
                                <tr><td><strong>取件码：</strong></td><td>
                                    ${order.pickup_code ? `<span class="badge bg-info">${order.pickup_code}</span>` : '<span class="text-muted">无</span>'}
                                </td></tr>
                                <tr><td><strong>提交时间：</strong></td><td>${new Date(order.created_at).toLocaleString('zh-CN')}</td></tr>
                `;
                
                if (order.status === 'settled' && order.settlement_amount) {
                    html += `<tr><td><strong>结算金额：</strong></td><td class="text-success">¥${parseFloat(order.settlement_amount).toFixed(2)}</td></tr>`;
                }
                
                if (order.settlement_info) {
                    html += `<tr><td><strong>结算信息：</strong></td><td>${order.settlement_info.replace(/\n/g, '<br>')}</td></tr>`;
                }
                
                if (order.notes) {
                    html += `<tr><td><strong>备注信息：</strong></td><td>${order.notes.replace(/\n/g, '<br>')}</td></tr>`;
                }
                
                html += `
                            </table>
                        </div>
                    </div>
                `;
                
                if (order.order_screenshot) {
                    html += `
                        <div class="mt-4">
                            <h6>订单截图</h6>
                            <img src="${order.screenshot_url}" class="img-fluid rounded border" style="max-height: 300px;">
                        </div>
                    `;
                }
                
                document.getElementById('orderDetailsContent').innerHTML = html;
            } else {
                document.getElementById('orderDetailsContent').innerHTML = `
                    <div class="alert alert-danger">${data.message || '加载失败'}</div>
                `;
            }
        })
        .catch(error => {
            document.getElementById('orderDetailsContent').innerHTML = `
                <div class="alert alert-danger">加载失败：${error.message}</div>
            `;
        });
}

// 初始化工具提示
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
    return new bootstrap.Tooltip(tooltipTriggerEl);
});
</script>